package com.mbigger.admin.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mbigger.admin.dto.AclModuleLevelDto;
import com.mbigger.admin.entity.Role;
import com.mbigger.admin.entity.User;
import com.mbigger.admin.param.RoleParam;
import com.mbigger.admin.service.RoleAclService;
import com.mbigger.admin.service.RoleService;
import com.mbigger.admin.service.RoleUserService;
import com.mbigger.admin.service.TreeService;
import com.mbigger.admin.service.UserService;
import com.mbigger.admin.util.StringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys/role")
public class RoleController {

	@Autowired
	private RoleService roleService;
	@Autowired
	private TreeService treeService;
	@Autowired
	private RoleAclService roleAclService;
	@Autowired
	private RoleUserService roleUserService;
	@Autowired
	private UserService userService;

	@PostMapping("/save")
	public void saveRole(RoleParam param) {
		roleService.save(param);
	}

	@PostMapping("/update")
	public void updateRole(RoleParam param) {
		roleService.update(param);
	}

	@GetMapping("/list")
	public List<Role> list() {
		return roleService.getAll();
	}

	@GetMapping("/tree")
	public List<AclModuleLevelDto> roleTree(int roleId) {
		return treeService.roleTree(roleId);
	}

	@PostMapping("/changeAcls")
	public void changeAcls(int roleId, String aclIds) {
		List<Integer> aclIdList = StringUtil.splitToListInt(aclIds);
		roleAclService.changeRoleAcls(roleId, aclIdList);
	}

	@PostMapping("/changeUsers")
	public void changeUsers(int roleId, String userIds) {
		List<Integer> userIdList = StringUtil.splitToListInt(userIds);
		roleUserService.changeRoleUsers(roleId, userIdList);
	}

	@GetMapping("/users")
	public Map<String, Object> users(int roleId) {
		List<User> selectedUserList = roleUserService.getListByRoleId(roleId);
		List<User> allUserList = userService.getAll();
		List<User> unselectedUserList = Lists.newArrayList();

		Set<Integer> selectedUserIdSet = selectedUserList.stream().map(user -> user.getId())
				.collect(Collectors.toSet());
		for (User user : allUserList) {
			if (user.getStatus() == 1 && !selectedUserIdSet.contains(user.getId())) {
				unselectedUserList.add(user);
			}
		}
		Map<String, Object> map = Maps.newHashMap();
		map.put("selected", selectedUserList);
		map.put("unselected", unselectedUserList);
		return map;
	}
}
